<?php defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * @author chaituan@126.com
 */
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
class Mall extends WechatCommon {
	
	function __construct(){
		parent::__construct();
		$this->load->model('admin/Goods_model');
	}
	
	function index() {
		$cid = Gets('cid');
		$this->load->model(array('admin/Ad_model'));
		$data['banner'] = $this->Ad_model->getItems(array('catid'=>5,'state'=>1));
		$where = array('thumb !='=>'');
		if($cid)$where['catid'] = $cid;
		//获取分类
		$this->load->model(array('admin/Goods_cat_model','admin/News_model'));
		$data['cat'] = $this->Goods_cat_model->get_catcachetree(false);
		$data['items'] =  $this->Goods_model->getItems($where,'id,names,thumb,sales,price','id desc',1,10,'',true);
		$data['pagemenu'] = $this->Goods_model->pagemenu;
		$this->load->view('mobile/mall/index',$data);
	}
	
	function goods_ajax(){
		if(is_ajax_request()){
			$this->load->model('admin/Goods_model');
			//商品列表条件
			$where = array(
					'thumb !='=>''
			);
			$page = Posts('page','checkid');
			$items =  $this->Goods_model->getItems($where,'id,names,thumb,sales,price','id desc',$page,4,'',true);
			$pagemenu = $this->Goods_model->pagemenu;
				
			AjaxResult(1, 'ok',array('items'=>$items,'page_end'=>$pagemenu['end']));
		}
	}
	
	//商品详情
	function detail(){
		$id = Gets('id','checkid');
		$data['item'] = $goods =  $this->Goods_model->getItem("id=$id",'sku_stock,sku_paths,thumb_arr,names,price,id');
		if(!$data['item'])showmessage('产品不存在','error');
		$stock = json_decode($goods['sku_stock'],true);
		$paths = json_decode($goods['sku_paths'],true);
		foreach ($paths as $k1=>$v1){
			$i=0;
			foreach ($v1['titles'] as $k2=>$v2){
				$ids[$k2] = $v1['symbols'][$k2];
				$sku['tree'][$k2]['k'] = $v2;
				foreach ($v1['s_options'][$k2] as $k3=>$v3){
					$sku['tree'][$k2]['v'][$k3]['name'] = $v3;
					$sku['tree'][$k2]['v'][$k3]['id'] = $i;
					$i++;
				}
				$sku['tree'][$k2]['k_s'] = 's'.($k2+1);
			}
			$sku['list'][] = array('id'=>$k1,'s1'=>$v1['symbols'][0],'s2'=>isset($v1['symbols'][1])?$v1['symbols'][1]:0,'s3'=>isset($v1['symbols'][2])?$v1['symbols'][2]:0,'price'=>$v1['price']*100,'stock_num'=>$stock[$k1]);
		}
		$sku['price'] = '1000';
		$sku['stock_num'] = 1000;
		$sku['collection_id'] = 0;
		$sku['none_sku'] = false;//是否是无规格商品
		$data['sku'] = $sku;
		$this->load->view('mobile/mall/detail',$data);
	}
	
	function save_goods(){
		if(is_ajax_request()){
			$data = Posts();
			$gid = $data['goodsId'];
			$price = $data['selectedSkuComb']['price']/100;
			$num = $data['selectedNum'];
			$goods = $this->Goods_model->getItem(array('id'=>$gid),'sku_paths,thumb,names');
			if(!$goods)AjaxResult_error('商品不存在');
			$paths = json_decode($goods['sku_paths'],true);
			$options = '已选：'.implode(' + ',$paths[$data['selectedSkuComb']['id']]['values']);
			$items = array(array(
					'id' => $gid.str_replace(',', '', $data['selectedSkuComb']['id']),//生成特别id
					'qty' => $num,//数量
					'price' => $price,//单架
					'name' => $goods['names'],//产品名字
					'options' => array('options' => $options,'selPath' => $data['selectedSkuComb']['id'],'thumb' =>$goods['thumb'],'total'=>$num*$price,'gid'=>$gid)
			));
			$this->session->set_userdata('goods_sku',$items);
			$this->session->set_userdata('source','direct');//直接购买
			AjaxResult_ok();
		}else{
			AjaxResult_error('错误请求');
		}
	}
	
	//购车跳转页面，然后确认订单
	function save_cart(){
		if(is_ajax_request()){
			$this->load->library('fcart');
			$cart = Posts('ids');//提交过来的产品id
			if(!$cart)AjaxResult_error('数据失效，请重新购买');
			foreach ($cart as $v){
				$items[] = $this->fcart->contents()[$v];
			}
			$this->session->set_userdata('goods_sku',$items);
			$this->session->set_userdata('source','cart');//购物车购买
			AjaxResult(1, '提交成功');
		}else{
			showmessage('错误请求','error','mobile/mall/index');
		}
	}
	
	function order(){
		$goods_sku = $this->session->goods_sku;
		if(!$goods_sku)showmessage('数据已经失效','info','mobile/mall/index');
		foreach ($goods_sku as $v){
			$idArr[] = $v['options']['gid'];
		}
		$idString = implode(',', array_unique($idArr));
		//检测实际价格
		$this->load->model('admin/Goods_model');
		$items = $this->Goods_model->getItems("id in ($idString)",'id,names,shopid,stock,price,catid,is_sku,is_stock,sku_price,sku_stock,sku_paths,thumb');
		if($items){
			//把查询出来的数组key 更换成id
			foreach ($items as $v){
				$newItem[$v['id']] = $v;
			}
			$total = 0;
			foreach ($goods_sku as $v){
				$goods = $newItem[$v['options']['gid']];//获取产品的所有参数
				if($goods['sku_paths']){//根据是否开始规格来判断产品是否已经没有库存了
					$sku_stock = json_decode($goods['sku_stock'],true);
					if($sku_stock[$v['options']['selPath']] <= 0)showmessage('抱歉，商品已经下架','error');
				}else{
					if($goods['stock'] <= 0)showmessage('抱歉，商品已经下架','error');
				}
				$sku_price = json_decode($goods['sku_price'],true);//获取当前产品的价格 转换成数组
				$price = $v['options']['selPath']?$sku_price[$v['options']['selPath']]:$goods['price'];//单价 根据选择路径获取真实数据价格 如果没有则正常价格
				$price_total = $price * $v['qty'];
				$newItems['detail'][$goods['shopid']][] = array(//通过店铺id 生成三维数组来区分
						'id'=>$goods['id'],
						'catid'=>$goods['catid'],
						'price'=>$price,
						'names'=>$goods['names'],
						'thumb'=>$goods['thumb'],
						'selPath'=>$v['options']['selPath'],
						'num' => $v['qty'],
						'options'=>$v['options']['options'],
						'prices' =>$price_total,
				);
				$newItems['total'][$goods['shopid']][] = $price_total;//为安全订单配置
				$total += $price_total;
			}
			//整合好的数据存入新的session
			$this->session->set_userdata('new_goods',$newItems);
			
			$data['total'] = $total * 100;
			$this->load->model('admin/Address_model');
			$address = $this->Address_model->getItems(array('id'=>$this->User['address']),'names as name,concat(province,city,county,address_detail) as address,tel,id');
			$data['address'] = $address?json_encode($address):'[]';
			$data['aid'] = $address?$address[0]['id']:'';//默认地址ID
			$data['items'] = json_encode($goods_sku);
			$this->load->view('mobile/mall/order',$data);
		}else{//当确认订单的时候，如果没有了库存，则不进去
			$this->load->library('fcart');//销毁购物车
			$this->fcart->destroy();
			showmessage('商品不存在','error','mobile/mall/index');
		}
	}
	
	//确认订单后，生成订单
	function create_order(){
		if(is_ajax_request()){
			$data = $this->safe_order(Posts());
			//生成订单
			$result = $this->Orderlists_model->add_batch($data);
			is_AjaxResult($result,'提交成功','提交失败');
		}else{
			showmessage('数据失效','waiting','mobile/mall/index');
		}
	}
	
	//生成安全订单
	private function safe_order($data){
		//多家店铺 考虑到 订单问题，支付完成后 异步通知只能传一个订单好，这时候我们设置一个pay_order_no 支付订单号来批量完成 支付状态
		$goods = $this->session->new_goods;
		if(!$goods)AjaxResult_error("时间太长，页面失效");
		$timg = time();
		$total = 0;
		$t = count($goods['detail']);//为了一下多个订单号，同时刷新支付状态
		$pay_order_no = order_trade_no().'X'.$t;
		$this->load->model(array('admin/Order_model','admin/Orderlists_model','admin/Address_model'));
		$address = $this->Address_model->getItem(array('id'=>$data['aid']),'names,concat(province,city,county,address_detail) as address,tel');
		
		foreach ($goods['detail'] as $k=>$item){//第一次循环生成 订单，
			$order_no = order_trade_no();
			$orderm = array(
					'openid'=>$this->User['openid'],
					'order_no'=>$order_no,
					'uid' =>$this->User['id'],
					'price' =>  array_sum($goods['total'][$k]),//计算出每家店铺 所有产品的总价格
					'addtime' =>$timg,
					'message' =>$data['message']?$data['message']:'',
					'shopid' =>$k,
					'pay_order_no' =>$pay_order_no,
					'delive' =>$data['delive'],
					'buy_name'=>$address['names'],'buy_mobile'=>$address['tel'],'buy_address'=>$address['address']
			);
			//插入数据库 生成订单
			$oid = $this->Order_model->add($orderm);
			foreach ($item as $v){//第二次循环生成订单的详情 ，也就是一个订单号多个子订单
				$datas[] = array(
						'oid' => $oid,
						'title'=>$v['names'],
						'order_no'=>$order_no,
						'uid'=>$this->User['id'],
						'prices'=>$v['price'],
						'thumb'=>$v['thumb'],
						'catid'=>$v['catid'],
						'gid'=>$v['id'],
						'sku'=>$v['options'],
						'num'=>$v['num'],
				);
				$names = $v['names'];
				$total += $v['prices'];
			}
		}
		//生成传递给微信的 参数
		if($this->session->source == 'direct'){
			$title = $names;
		}else{
			$title = '多产品合并支付';
		}
		$wechat = array(
				'openid'=>$this->User['openid'],
				'title'=>$title,
				'out_trade_no'=>$pay_order_no,
				'total_fee'=>$total,
				'product_id'=>1
		);
		if($wechat){//设置订单信息
			$this->session->set_userdata('order_info',$wechat);
		}
// 		if(isset($goods['sku'])&&$goods['sku']){//更新库存
// 			$this->load->model('admin/Goods_model');
// 			$this->Goods_model->update_batchs($goods['sku'],'id');
// 		}
		if($this->session->source == 'cart'){//销毁购车
			$this->load->library('fcart');
			$this->fcart->destroy();
		}
		return $datas;
	}
	//收银台
	function syt(){
		$order_info = $this->session->order_info;
		if($order_info){
			$this->load->library('wechat/wechat_pay_api');//支付功能
			$data['pay_api'] = $this->wechat_pay_api->pay($order_info);
			$data['total'] = $order_info['total_fee'];
			$data['pay_order_no'] = $order_info['out_trade_no'];
			$this->session->unset_userdata(array('order_info','new_goods','goods_sku'));//销毁数据
			$this->load->view('mobile/order/syt',$data);
		}else{
			showmessage('数据失效','waiting','mobile/order/lists/id-1');
		}
	}
	
	//未支付收银台s
	function syts(){
		$id = Gets('id','checkid');
		if($id){
			$items = $this->Order_model->getItems_join(array('order_lists'=>'order.id=order_lists.oid'),"order.id=$id",'order.price,order.pay_order_no,order_lists.title');
			$count = count($items);
			$item = $items[0];
			if($count>1){
				$title = '多产品合并支付';
			}else{
				$title = $item['title'];
			}
			$wechat = array(
					'openid'=>$this->User['openid'],
					'title'=>$title,
					'out_trade_no'=>$item['pay_order_no'],
					'total_fee'=>$item['price'],
					'product_id'=>1
			);
			$this->load->library('wechat/wechat_pay_api');//支付功能
			$data['pay_api'] = $this->wechat_pay_api->pay($wechat);
			$data['total'] = $item['price'];
			$data['pay_order_no'] = $item['pay_order_no'];
			$this->load->view('mobile/order/syt',$data);
		}else{
			showmessage('数据失效','waiting','mobile/order/lists/id-1');
		}
	}
	
	function pay(){
		if(is_ajax_request()){
			$goods_sku = $this->session->goods_sku;
			if(!$goods_sku)showmessage('数据已经失效','info','mobile/mall/index');
			$this->load->model('admin/Order_model');
			$data = Posts('data');
			$id = Posts('id','num');
			$item = $this->Goods_model->getItem("id=$id");
			$order_no = order_trade_no();
			$total = $item['price'] * $data['num'];
			$orderm = array(
					'order_no'=>$order_no,
					'title'=>$item['names'],
					'uid' =>$this->User['id'],
					'price' =>  $item['price'],
					'prices' =>  $total,
					'state' => 1,
					'addtime' =>time(),
					'num'=>$data['num'],
					'thumb'=>$item['thumb'],
					'message' =>$data['message'],
					'buy_name'=>$data['buy_name'],'buy_mobile'=>$data['buy_mobile'],'buy_address'=>$data['buy_address']
			
			);
			$result = $this->Order_model->add($orderm);
			if($result){
				//获取微信支付基础配置
				$options = ['app_id'=>WX_APPID,'secret'=>WX_APPSecret,'payment' => ['merchant_id'=> WX_MCHID,'key'=> WX_KEY,'cert_path'=> SSLCERT_PATH,'key_path'=> SSLKEY_PATH,'notify_url'=> NOTIFY_URL_MALL]];
				$app = new Application($options);
				$payment = $app->payment;
				//订单参数
				$attributes = ['trade_type'=>'JSAPI','body'=> $item['names'],'detail'=> $item['names'],
				'out_trade_no'=>$order_no,'total_fee'=> $total*100,'notify_url'=> NOTIFY_URL_MALL,'openid'=> $this->User['openid']];
				$order = new Order($attributes);
				$result = $payment->prepare($order);//下单接口
				if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
					$prepayId = $result->prepay_id;
					$arr = $payment->configForPayment($prepayId,false);
				}
				AjaxResult(1,'', $arr);
			}else{
				AjaxResult_error("支付异常0001");
			}
		}
		
	}
	
}
